package com.thread.prodcustrom;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TestReentrantLockConsumerAndProducer {

	/*当前生成数量*/
	static int currentNum = 0;
	/*最大生成数量*/
	static int MAX_NUM = 10;
	/*最小消费数量*/
	static int MIN_NUM = 0;
	//创建一个锁对象
	private static Lock lock = new ReentrantLock();
	//缓冲区已空的变量
	private static final Condition emptyCondition = lock.newCondition();
	//缓冲区已满的变量
	private static final Condition fullCondition = lock.newCondition();

	public static void main(String args[]) {
		//创建一个生产者
		new Thread(new Producer()).start();

		//创建两个消费者
		new Thread(new Consumer()).start();
		new Thread(new Consumer()).start();
	}


	static class Producer implements Runnable {
		public void product() {
			while (true) {
				try {
					Thread.sleep(10);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				lock.lock();
				currentNum++;
				System.out.println("Producer now product num:" + currentNum);
				if (currentNum == MAX_NUM) {
					emptyCondition.signal();
					try {
						fullCondition.await();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				lock.unlock();

			}
		}

		@Override
		public void run() {
			product();
		}
	}

	static class Consumer implements Runnable {
		public void consume() {
			while (true) {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				lock.lock();
				if (currentNum == MIN_NUM) {
					fullCondition.signal();
					try {
						emptyCondition.await();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					continue;
				}
				System.out.println(new StringBuilder(Thread.currentThread().getName())
						.append(" Consumer now consumption num:").append(currentNum));
				currentNum--;

				lock.unlock();
			}
		}

		@Override
		public void run() {
			consume();
		}
	}
}
